package cn.com.ry.framework.monitormeter.instrument.binder;

import cn.com.ry.framework.monitormeter.metric.jdbc.*;
import cn.com.ry.framework.monitormeter.util.Assert;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JDBCMonitor {
    private String dataSoruceName;
    private DataSource dataSource;
    private List<JDBCBean> jdbcBeanList = new ArrayList<JDBCBean>();


    public JDBCMonitor() {

    }

    public JDBCMonitor(String dataSoruceName, DataSource dataSource) {
        this.dataSoruceName = dataSoruceName;
        this.dataSource = dataSource;
    }

    //添加连接池指标
    public void buildDataSourcePoolMetrics(MeterRegistry meterRegistry, Map<String, DataSource> dataSourceMap) {
        //判断连接池的类型
        if (dataSourceMap != null) {
            for (Map.Entry<String, DataSource> entry : dataSourceMap.entrySet()) {
                String key = entry.getKey();
                DataSource dataSource = entry.getValue();
                String dataSourceName = dataSource.getClass().getName();
                if (dataSourceName.equals("com.alibaba.druid.pool.DruidDataSource")) {
                    new DruidDataSourcePoolMetrics(key, dataSource).bindTo(meterRegistry);
                } else if (dataSourceName.equals("org.apache.commons.dbcp.BasicDataSource")) {
                    new DbcpDataSourcePoolMetrics(key, dataSource).bindTo(meterRegistry);
                } else if (dataSourceName.equals("com.zaxxer.hikari.HikariDataSource")) {
                    new HikariDataSourcePoolMetrics(key, dataSource).bindTo(meterRegistry);
                }
            }
        }
    }


    /**
     * 添加监控sql
     *
     * @param name 指标名称
     * @param sql  指标sql
     * @return
     */
    public JDBCMonitor query(String name, String sql) {
        //去重
        for (JDBCBean jdbcBean : jdbcBeanList) {
            if (jdbcBean.getName().equals(name) && jdbcBean.getSql().equals(sql)) {
                return this;
            }
        }
        JDBCBean jdbcBean = new JDBCBean(name, sql);
        jdbcBeanList.add(jdbcBean);
        return this;
    }


    /**
     * 添加表数据量监控
     *
     * @param meterRegistry 数据源名称
     */

    public void buildQueryMetrics(MeterRegistry meterRegistry) {
        buildQueryMetrics(meterRegistry, Tags.of("remark", "数据库指标查询"));
    }

    public void buildQueryMetrics(MeterRegistry meterRegistry, Iterable<Tag> tags) {
        Assert.notNull(dataSource, "dataSource不能为空");
        new DBTableMetrics(dataSource, dataSoruceName, jdbcBeanList, tags).bindTo(meterRegistry);
    }

    //添加健康状态指标

    //添加异常情况指标
}
